<template>
  <div class="register-container">
    <div class="register-wrapper">
      <div class="title-container">
        <h2 class="title">商家入驻申请</h2>
        <p class="subtitle">请填写真实信息，我们将在1-3个工作日内完成审核</p>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        label-width="120px"
        label-position="left"
      >
        <!-- 步骤指示器 -->
        <el-steps :active="currentStep" align-center class="steps">
          <el-step title="基本信息" />
          <el-step title="身份认证" />
          <el-step title="资质上传" />
          <el-step title="地区选择" />
        </el-steps>

        <!-- 第一步：基本信息 -->
        <div v-show="currentStep === 0" class="step-content">
          <h3 class="step-title">基本信息</h3>

          <el-form-item label="商家名称" prop="merchantName">
            <el-input
              v-model="registerForm.merchantName"
              placeholder="请输入商家名称"
              maxlength="50"
            />
          </el-form-item>

          <el-form-item label="商家类型" prop="merchantType">
            <el-radio-group v-model="registerForm.merchantType">
              <el-radio label="individual">个人商家</el-radio>
              <el-radio label="enterprise">企业商家</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="联系人" prop="contactName">
            <el-input
              v-model="registerForm.contactName"
              placeholder="请输入联系人姓名"
              maxlength="20"
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
            />
          </el-form-item>

          <el-form-item label="验证码" prop="verificationCode">
            <div class="verification-input">
              <el-input
                v-model="registerForm.verificationCode"
                placeholder="请输入验证码"
                maxlength="6"
                style="flex: 1; margin-right: 10px;"
              />
              <el-button
                :disabled="!canSendCode || codeCountdown > 0"
                @click="sendVerificationCode"
                :loading="sendingCode"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s后重发` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="电子邮箱" prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱地址"
              type="email"
            />
          </el-form-item>

          <el-form-item label="登录密码" prop="password">
            <el-input
              v-model="registerForm.password"
              :type="passwordType"
              placeholder="请输入登录密码"
              show-password
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              :type="passwordType"
              placeholder="请再次输入密码"
              show-password
            />
          </el-form-item>
        </div>

        <!-- 第二步：身份认证 -->
        <div v-show="currentStep === 1" class="step-content">
          <h3 class="step-title">身份认证</h3>

          <el-form-item label="真实姓名" prop="realName">
            <el-input
              v-model="registerForm.realName"
              placeholder="请输入身份证上的真实姓名"
              maxlength="20"
            />
          </el-form-item>

          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="registerForm.idCard"
              placeholder="请输入18位身份证号码"
              maxlength="18"
            />
          </el-form-item>

          <el-form-item label="身份证正面" prop="idCardFront">
            <div class="upload-section">
              <el-upload
                class="id-card-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleIdCardFrontSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                :headers="uploadHeaders"
                accept="image/*"
              >
                <img
                  v-if="registerForm.idCardFront"
                  :src="registerForm.idCardFront"
                  class="id-card-image"
                />
                <div v-else class="upload-placeholder">
                  <el-icon><Plus /></el-icon>
                  <div class="upload-text">上传身份证正面</div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <p>请上传身份证正面照片</p>
                <p>确保头像和个人信息清晰可见</p>
                <p>支持JPG、PNG格式，大小不超过5MB</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="身份证反面" prop="idCardBack">
            <div class="upload-section">
              <el-upload
                class="id-card-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleIdCardBackSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                :headers="uploadHeaders"
                accept="image/*"
              >
                <img
                  v-if="registerForm.idCardBack"
                  :src="registerForm.idCardBack"
                  class="id-card-image"
                />
                <div v-else class="upload-placeholder">
                  <el-icon><Plus /></el-icon>
                  <div class="upload-text">上传身份证反面</div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <p>请上传身份证反面照片</p>
                <p>确保国徽和签发机关清晰可见</p>
                <p>支持JPG、PNG格式，大小不超过5MB</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="人脸识别" prop="faceVerification">
            <div class="face-verification-section">
              <div class="face-verification-content">
                <div v-if="!registerForm.faceVerification" class="face-capture">
                  <div class="face-capture-area">
                    <video
                      v-if="showCamera"
                      ref="videoRef"
                      autoplay
                      playsinline
                      class="face-video"
                    ></video>
                    <div v-else class="face-placeholder">
                      <el-icon class="face-icon"><Camera /></el-icon>
                      <p>请进行人脸识别验证</p>
                      <p class="face-tips">确保光线充足，面部清晰可见</p>
                    </div>
                  </div>
                  <div class="face-actions">
                    <el-button
                      v-if="!showCamera"
                      type="primary"
                      @click="startFaceCapture"
                      :loading="startingCamera"
                    >
                      开始人脸识别
                    </el-button>
                    <div v-else class="capture-buttons">
                      <el-button @click="stopFaceCapture">取消</el-button>
                      <el-button type="primary" @click="captureFace" :loading="capturingFace">
                        拍照验证
                      </el-button>
                    </div>
                  </div>
                </div>
                <div v-else class="face-success">
                  <el-icon class="success-icon"><SuccessFilled /></el-icon>
                  <p>人脸识别验证成功</p>
                  <el-button size="small" @click="resetFaceVerification">重新验证</el-button>
                </div>
              </div>
              <div class="face-tips-panel">
                <h4>人脸识别说明：</h4>
                <ul>
                  <li>请确保本人操作，不得代替他人验证</li>
                  <li>保持面部正对摄像头，表情自然</li>
                  <li>确保光线充足，避免逆光或阴影</li>
                  <li>摘下帽子、墨镜等遮挡物</li>
                  <li>验证信息将与身份证信息进行比对</li>
                </ul>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- 第三步：资质上传 -->
        <div v-show="currentStep === 2" class="step-content">
          <h3 class="step-title">资质上传</h3>

          <el-form-item label="营业执照号" prop="businessLicenseNumber">
            <el-input
              v-model="registerForm.businessLicenseNumber"
              placeholder="请输入营业执照注册号"
              maxlength="30"
            />
          </el-form-item>

          <el-form-item label="营业执照" prop="businessLicense">
            <div class="upload-section">
              <el-upload
                class="license-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleBusinessLicenseSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                :headers="uploadHeaders"
                accept="image/*,.pdf"
              >
                <img
                  v-if="registerForm.businessLicense && isImageFile(registerForm.businessLicense)"
                  :src="registerForm.businessLicense"
                  class="license-image"
                />
                <div v-else-if="registerForm.businessLicense" class="file-info">
                  <el-icon><Document /></el-icon>
                  <span>营业执照已上传</span>
                </div>
                <div v-else class="upload-placeholder">
                  <el-icon><Plus /></el-icon>
                  <div class="upload-text">上传营业执照</div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <p>请上传营业执照扫描件或照片</p>
                <p>确保证件信息清晰完整</p>
                <p>支持JPG、PNG、PDF格式，大小不超过10MB</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="法人姓名" prop="legalPerson">
            <el-input
              v-model="registerForm.legalPerson"
              placeholder="请输入法人代表姓名"
              maxlength="20"
            />
          </el-form-item>

          <el-form-item label="法人身份证" prop="legalPersonId">
            <el-input
              v-model="registerForm.legalPersonId"
              placeholder="请输入法人身份证号码"
              maxlength="18"
            />
          </el-form-item>

          <el-form-item label="洗护服务类型" prop="serviceTypes">
            <div class="service-types-section">
              <div class="service-types-grid">
                <div
                  v-for="service in laundryServiceOptions"
                  :key="service.value"
                  class="service-type-item"
                  :class="{ active: registerForm.serviceTypes.includes(service.value) }"
                  @click="toggleServiceType(service.value)"
                >
                  <div class="service-icon" :class="service.value">
                    <el-icon v-if="service.icon" :class="service.icon"></el-icon>
                    <span v-else>{{ service.emoji }}</span>
                  </div>
                  <div class="service-name">{{ service.label }}</div>
                  <div class="service-desc">{{ service.description }}</div>
                </div>
              </div>
              <div class="service-tips">
                <p>请选择您要提供的洗护服务类型（可多选）</p>
                <p>选择的服务类型将影响您接收到的订单类型</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="其他经营范围" prop="businessScope">
            <el-select
              v-model="registerForm.businessScope"
              multiple
              filterable
              placeholder="请选择其他经营范围（可选）"
              style="width: 100%"
            >
              <el-option
                v-for="item in businessScopeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 第四步：地区选择 -->
        <div v-show="currentStep === 3" class="step-content">
          <h3 class="step-title">地区选择</h3>

          <el-form-item label="所在地区" prop="region">
            <el-cascader
              v-model="registerForm.region"
              :options="regionOptions"
              placeholder="请选择省市区"
              :props="cascaderProps"
              clearable
              filterable
              style="width: 100%"
              @change="handleRegionChange"
            />
          </el-form-item>

          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="registerForm.address"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址（街道、门牌号等）"
              maxlength="200"
            />
          </el-form-item>

          <el-form-item label="服务范围" prop="serviceArea">
            <el-input-number
              v-model="registerForm.serviceArea"
              :min="1"
              :max="50"
              :step="1"
              placeholder="服务半径"
              style="width: 200px"
            />
            <span style="margin-left: 10px">公里</span>
          </el-form-item>

          <el-form-item label="营业时间" prop="businessHours">
            <el-time-picker
              v-model="registerForm.businessHours"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              value-format="HH:mm"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="商家简介" prop="description">
            <el-input
              v-model="registerForm.description"
              type="textarea"
              :rows="4"
              placeholder="请简要介绍您的商家特色和服务"
              maxlength="500"
            />
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="registerForm.agreement">
              我已阅读并同意
              <el-link type="primary" @click="showAgreement">《商家入驻协议》</el-link>
              和
              <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
            </el-checkbox>
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button
            v-if="currentStep > 0"
            @click="prevStep"
            size="large"
          >
            上一步
          </el-button>

          <el-button
            v-if="currentStep < 3"
            type="primary"
            @click="nextStep"
            size="large"
          >
            下一步
          </el-button>

          <el-button
            v-if="currentStep === 3"
            type="primary"
            :loading="loading"
            @click="handleRegister"
            size="large"
            :disabled="!registerForm.agreement"
          >
            提交申请
          </el-button>
        </div>

        <div class="tips">
          <span>已有账号? </span>
          <router-link to="/login" class="link-type">
            立即登录
          </router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Document } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const currentStep = ref(0)
const passwordType = ref('password')
const registerFormRef = ref(null)
const sendingCode = ref(false)
const codeCountdown = ref(0)
const canSendCode = ref(false)

// 表单数据
const registerForm = reactive({
  // 基本信息
  merchantName: '',
  merchantType: 'individual',
  contactName: '',
  phone: '',
  verificationCode: '',
  email: '',
  password: '',
  confirmPassword: '',

  // 身份认证
  realName: '',
  idCard: '',
  idCardFront: '',
  idCardBack: '',

  // 资质上传
  businessLicenseNumber: '',
  businessLicense: '',
  legalPerson: '',
  legalPersonId: '',
  serviceTypes: [], // 洗护服务类型
  businessScope: [],

  // 地区选择
  region: [],
  address: '',
  serviceArea: 5,
  businessHours: [],
  description: '',
  agreement: false
})

// 上传配置
const uploadUrl = '/api/upload'
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem('token') || ''}`
}))

// 洗护服务类型选项
const laundryServiceOptions = [
  {
    value: 'clothes',
    label: '洗衣服',
    description: '普通衣物清洗、精洗、干洗等',
    emoji: '👔'
  },
  {
    value: 'shoes',
    label: '洗鞋',
    description: '运动鞋、皮鞋、靴子清洗护理',
    emoji: '👟'
  },
  {
    value: 'pets',
    label: '洗萌宠',
    description: '宠物洗澡、美容、护理服务',
    emoji: '🐕'
  },
  {
    value: 'bags',
    label: '洗包包',
    description: '皮包、布包、背包清洗保养',
    emoji: '👜'
  },
  {
    value: 'bedding',
    label: '洗被子',
    description: '被子、床单、枕头等床品清洗',
    emoji: '🛏️'
  },
  {
    value: 'car',
    label: '洗车',
    description: '汽车内外清洗、打蜡、美容',
    emoji: '🚗'
  },
  {
    value: 'home',
    label: '上门清洗',
    description: '家庭深度清洁、家具清洗',
    emoji: '🏠'
  },
  {
    value: 'plumbing',
    label: '疏通厕所',
    description: '管道疏通、厕所维修清洁',
    emoji: '🚽'
  }
]

// 其他经营范围选项
const businessScopeOptions = [
  { label: '美容服务', value: 'beauty' },
  { label: '美发服务', value: 'hair' },
  { label: '美甲服务', value: 'nail' },
  { label: '按摩服务', value: 'massage' },
  { label: '家政服务', value: 'housekeeping' },
  { label: '维修服务', value: 'repair' },
  { label: '其他服务', value: 'other' }
]

// 地区选择配置
const cascaderProps = {
  value: 'code',
  label: 'name',
  children: 'children',
  emitPath: false
}

// 地区数据
const regionOptions = ref([
  {
    code: '110000',
    name: '北京市',
    children: [
      {
        code: '110100',
        name: '市辖区',
        children: [
          { code: '110101', name: '东城区' },
          { code: '110102', name: '西城区' },
          { code: '110105', name: '朝阳区' },
          { code: '110106', name: '丰台区' },
          { code: '110107', name: '石景山区' },
          { code: '110108', name: '海淀区' },
          { code: '110109', name: '门头沟区' },
          { code: '110111', name: '房山区' },
          { code: '110112', name: '通州区' },
          { code: '110113', name: '顺义区' }
        ]
      }
    ]
  },
  {
    code: '310000',
    name: '上海市',
    children: [
      {
        code: '310100',
        name: '市辖区',
        children: [
          { code: '310101', name: '黄浦区' },
          { code: '310104', name: '徐汇区' },
          { code: '310105', name: '长宁区' },
          { code: '310106', name: '静安区' },
          { code: '310107', name: '普陀区' },
          { code: '310109', name: '虹口区' },
          { code: '310110', name: '杨浦区' },
          { code: '310112', name: '闵行区' },
          { code: '310113', name: '宝山区' },
          { code: '310114', name: '嘉定区' }
        ]
      }
    ]
  },
  {
    code: '440000',
    name: '广东省',
    children: [
      {
        code: '440100',
        name: '广州市',
        children: [
          { code: '440103', name: '荔湾区' },
          { code: '440104', name: '越秀区' },
          { code: '440105', name: '海珠区' },
          { code: '440106', name: '天河区' },
          { code: '440111', name: '白云区' },
          { code: '440112', name: '黄埔区' },
          { code: '440113', name: '番禺区' },
          { code: '440114', name: '花都区' },
          { code: '440115', name: '南沙区' },
          { code: '440117', name: '从化区' }
        ]
      },
      {
        code: '440300',
        name: '深圳市',
        children: [
          { code: '440303', name: '罗湖区' },
          { code: '440304', name: '福田区' },
          { code: '440305', name: '南山区' },
          { code: '440306', name: '宝安区' },
          { code: '440307', name: '龙岗区' },
          { code: '440308', name: '盐田区' },
          { code: '440309', name: '龙华区' },
          { code: '440310', name: '坪山区' },
          { code: '440311', name: '光明区' }
        ]
      }
    ]
  }
])

// 表单验证规则
const registerRules = {
  // 基本信息验证
  merchantName: [
    { required: true, message: '请输入商家名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商家名称长度在2到50个字符', trigger: 'blur' }
  ],
  merchantType: [
    { required: true, message: '请选择商家类型', trigger: 'change' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '联系人姓名长度在2到20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6到20个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],

  // 身份认证验证
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5·]+$/, message: '请输入正确的中文姓名', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入正确的身份证号码',
      trigger: 'blur'
    }
  ],
  idCardFront: [
    { required: true, message: '请上传身份证正面照片', trigger: 'change' }
  ],
  idCardBack: [
    { required: true, message: '请上传身份证反面照片', trigger: 'change' }
  ],

  // 资质上传验证
  businessLicenseNumber: [
    { required: true, message: '请输入营业执照号', trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  legalPerson: [
    { required: true, message: '请输入法人姓名', trigger: 'blur' }
  ],
  legalPersonId: [
    { required: true, message: '请输入法人身份证号', trigger: 'blur' },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入正确的身份证号码',
      trigger: 'blur'
    }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  serviceTypes: [
    { required: true, message: '请至少选择一种洗护服务类型', trigger: 'change' }
  ],
  businessScope: [
    { required: false, message: '请选择其他经营范围', trigger: 'change' }
  ],

  // 地区选择验证
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 200, message: '详细地址长度在5到200个字符', trigger: 'blur' }
  ],
  serviceArea: [
    { required: true, message: '请设置服务范围', trigger: 'blur' }
  ],
  businessHours: [
    { required: true, message: '请选择营业时间', trigger: 'change' }
  ]
}

// 方法
const nextStep = async () => {
  try {
    // 验证当前步骤的表单
    const fieldsToValidate = getFieldsForStep(currentStep.value)
    if (fieldsToValidate.length > 0) {
      await registerFormRef.value.validateField(fieldsToValidate)
    }

    if (currentStep.value < 3) {
      currentStep.value++
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const getFieldsForStep = (step) => {
  const stepFields = {
    0: ['merchantName', 'merchantType', 'contactName', 'phone', 'verificationCode', 'email', 'password', 'confirmPassword'],
    1: ['realName', 'idCard', 'idCardFront', 'idCardBack'],
    2: ['businessLicenseNumber', 'businessLicense', 'legalPerson', 'legalPersonId', 'serviceTypes'],
    3: ['region', 'address', 'serviceArea', 'businessHours']
  }
  return stepFields[step] || []
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!registerForm.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }

  if (!/^1[3456789]\d{9}$/.test(registerForm.phone)) {
    ElMessage.warning('请输入正确的手机号格式')
    return
  }

  try {
    sendingCode.value = true

    // 模拟发送验证码API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('验证码已发送，请注意查收')

    // 开始倒计时
    codeCountdown.value = 60
    const timer = setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

  } catch (error) {
    ElMessage.error('验证码发送失败，请重试')
  } finally {
    sendingCode.value = false
  }
}

// 切换服务类型选择
const toggleServiceType = (serviceType) => {
  const index = registerForm.serviceTypes.indexOf(serviceType)
  if (index > -1) {
    registerForm.serviceTypes.splice(index, 1)
  } else {
    registerForm.serviceTypes.push(serviceType)
  }
}

// 上传相关方法
const beforeUpload = (file) => {
  const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage && !isPDF) {
    ElMessage.error('只支持JPG、PNG和PDF格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return false
  }
  return true
}

const handleIdCardFrontSuccess = (response) => {
  registerForm.idCardFront = response.data.url
  ElMessage.success('身份证正面上传成功')
}

const handleIdCardBackSuccess = (response) => {
  registerForm.idCardBack = response.data.url
  ElMessage.success('身份证反面上传成功')
}

const handleBusinessLicenseSuccess = (response) => {
  registerForm.businessLicense = response.data.url
  ElMessage.success('营业执照上传成功')
}

const handleUploadError = () => {
  ElMessage.error('文件上传失败，请重试')
}

const isImageFile = (url) => {
  return /\.(jpg|jpeg|png|gif)$/i.test(url)
}

// 地区选择变化
const handleRegionChange = (value) => {
  console.log('选择的地区:', value)
}

// 显示协议
const showAgreement = () => {
  ElMessageBox.alert('这里是商家入驻协议内容...', '商家入驻协议', {
    confirmButtonText: '确定'
  })
}

const showPrivacy = () => {
  ElMessageBox.alert('这里是隐私政策内容...', '隐私政策', {
    confirmButtonText: '确定'
  })
}

// 提交注册
const handleRegister = async () => {
  try {
    const valid = await registerFormRef.value.validate()
    if (!valid) return

    if (!registerForm.agreement) {
      ElMessage.warning('请先阅读并同意相关协议')
      return
    }

    loading.value = true

    // 构建提交数据
    const submitData = {
      merchantName: registerForm.merchantName,
      merchantType: registerForm.merchantType,
      contactName: registerForm.contactName,
      phone: registerForm.phone,
      verificationCode: registerForm.verificationCode,
      email: registerForm.email,
      password: registerForm.password,
      realName: registerForm.realName,
      idCard: registerForm.idCard,
      idCardFront: registerForm.idCardFront,
      idCardBack: registerForm.idCardBack,
      businessLicenseNumber: registerForm.businessLicenseNumber,
      businessLicense: registerForm.businessLicense,
      legalPerson: registerForm.legalPerson,
      legalPersonId: registerForm.legalPersonId,
      serviceTypes: registerForm.serviceTypes, // 洗护服务类型
      businessScope: registerForm.businessScope,
      region: registerForm.region,
      address: registerForm.address,
      serviceArea: registerForm.serviceArea,
      businessHours: registerForm.businessHours,
      description: registerForm.description
    }

    // 调用注册API
    await userStore.registerMerchant(submitData)

    ElMessage.success('申请提交成功！我们将在1-3个工作日内完成审核，请耐心等待。')

    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error(error.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}

// 监听手机号变化
watch(() => registerForm.phone, (newPhone) => {
  canSendCode.value = /^1[3456789]\d{9}$/.test(newPhone)
})

// 页面初始化
onMounted(() => {
  console.log('商家注册页面已加载')
})
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.register-wrapper {
  width: 100%;
  max-width: 800px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.title-container {
  text-align: center;
  padding: 40px 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;

  .title {
    margin: 0 0 10px;
    font-size: 28px;
    font-weight: 700;
  }

  .subtitle {
    margin: 0;
    font-size: 14px;
    opacity: 0.9;
  }
}

.register-form {
  padding: 40px;
}

.steps {
  margin-bottom: 40px;

  :deep(.el-step__title) {
    font-size: 14px;
    font-weight: 600;
  }
}

.step-content {
  margin-bottom: 40px;
}

.step-title {
  margin: 0 0 30px;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  border-bottom: 2px solid #e5e7eb;
  padding-bottom: 10px;
}

.upload-section {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.id-card-uploader,
.license-uploader {
  .upload-placeholder {
    width: 200px;
    height: 120px;
    border: 2px dashed #d1d5db;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      border-color: #667eea;
      background-color: #f8fafc;
    }

    .el-icon {
      font-size: 32px;
      color: #9ca3af;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 14px;
      color: #6b7280;
    }
  }

  .id-card-image,
  .license-image {
    width: 200px;
    height: 120px;
    object-fit: cover;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
  }

  .file-info {
    width: 200px;
    height: 120px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f9fafb;

    .el-icon {
      font-size: 32px;
      color: #667eea;
      margin-bottom: 8px;
    }

    span {
      font-size: 14px;
      color: #374151;
    }
  }
}

.upload-tips {
  flex: 1;

  p {
    margin: 0 0 5px;
    font-size: 12px;
    color: #6b7280;
    line-height: 1.4;
  }
}

.verification-input {
  display: flex;
  align-items: center;
  width: 100%;
}

.service-types-section {
  .service-types-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
  }

  .service-type-item {
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: white;

    &:hover {
      border-color: #667eea;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
    }

    &.active {
      border-color: #667eea;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;

      .service-icon {
        background: rgba(255, 255, 255, 0.2);
        color: white;
      }

      .service-name {
        color: white;
      }

      .service-desc {
        color: rgba(255, 255, 255, 0.9);
      }
    }

    .service-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: #f3f4f6;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 12px;
      font-size: 24px;
      transition: all 0.3s ease;
    }

    .service-name {
      font-size: 16px;
      font-weight: 600;
      color: #1f2937;
      margin-bottom: 8px;
      transition: color 0.3s ease;
    }

    .service-desc {
      font-size: 12px;
      color: #6b7280;
      line-height: 1.4;
      transition: color 0.3s ease;
    }
  }

  .service-tips {
    background: #f8fafc;
    border-radius: 8px;
    padding: 15px;
    border-left: 4px solid #667eea;

    p {
      margin: 0 0 5px;
      font-size: 13px;
      color: #6b7280;
      line-height: 1.4;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px solid #e5e7eb;
}

.tips {
  text-align: center;
  margin-top: 30px;
  font-size: 14px;
  color: #6b7280;

  .link-type {
    color: #667eea;
    text-decoration: none;
    font-weight: 600;

    &:hover {
      text-decoration: underline;
    }
  }
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 600;
  padding: 12px 24px;
}

:deep(.el-radio__label) {
  font-weight: 500;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .register-container {
    padding: 10px;
  }

  .register-wrapper {
    max-width: 100%;
  }

  .title-container,
  .register-form {
    padding: 20px;
  }

  .upload-section {
    flex-direction: column;
    gap: 15px;
  }

  .form-actions {
    flex-direction: column;
    gap: 15px;
  }
}
</style>

<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .register-container .el-input input {
    color: $cursor;
  }
}

.register-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .register-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $light_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $light_gray;
    cursor: pointer;
    user-select: none;
  }

  .link-type {
    color: #409EFF;
    text-decoration: none;
  }
}
</style>